<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2021/8/27
 * Time: 下午4:25
 */

namespace app\web\controller;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\Recode;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\lib\Jssdk;
use think\Controller;
use think\Env;
use think\Exception;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * 直播间H5
 * Class Live
 * @support v2.7.0
 * @package app\web\controller
 */
class Live extends Controller
{
    public function index()
    {
        $liveId = input('live_id/d', 0);
        $h = input('h/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        if ($liveId <= 0)
        {
            throw new ApiException('主播未找到！');
        }
        $header = [
            'version' => $this->request->header('version'),
            'time' => $this->request->header('time'),
            'distinct-id' => $this->request->header('distinct-id'),
            'phone-version' => $this->request->header('phone-version'),
            'app-type' => $this->request->header('app-type'),
            'did' => $this->request->header('did'),
            'access-token' => $this->request->header('access-token'),
            'model' => $this->request->header('model'),
            'sign' => $this->request->header('sign'),
        ];
        $isInApp = 0;
        try
        {
            $config = config('app');
            if (isset($header['sign']) &&
                strpos($config['app_types'], $header['app-type']) !== true)
            {
                // 在准了App中
                if (IAuth::checkSignPass($header, 'app'))
                {
                    $isInApp = 1;
                }// 在直播端中
                elseif (IAuth::checkSignPass($header, 'live_app'))
                {
                    $isInApp = 2;
                }
            }
            // 后台管理
            if (input('pc/d', 0) === 1)
            {
                $isInApp = 3;
//            $header = [
//                'version' => '1.0.0',
//                'time' => $this->request->time(),
//                'distinct-id' => $this->request->header('distinct-id'),
//                'phone-version' => $this->request->header('phone-version'),
//                'app-type' => 'admin',
//                'did' => $this->request->header('did'),
//                'access-token' => $this->request->header('access-token'),
//                'model' => $this->request->header('model'),
//                'sign' => $this->request->header('sign'),
//            ];
            }
            $sign = 0;
            $uid = 0;
            $uen = '';
            if ($header['access-token'])
            {
                //校验token
                try
                {
                    $auth = new Auth();
                    $auth->checkRequestAuth();
                    if ($auth->user['rid'])
                    {
                        $recordInfo = (new Recode())->getInfoById($auth->user['rid']);
                        $sign = (int)(explode('-', $recordInfo['sun'])[0]);
                    }
                    $uid = $auth->user['id'];
                    $uen = $auth->user['uen'];
                }
                catch (Exception $e)
                {
                    $uid = 0;
                }
            }

            if ($this->isInWx())
            {
                //微信分享的获取微信js签名
                $signPackage = (new Jssdk())->getSignPackage();
            } else
            {
                $signPackage = [];
            }
            $signPackage = json_encode($signPackage, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            //获取周运信息
            $randSign = random_int(1, 12);
            $week = (new Fortune())->weekInfo($randSign);
            // 直播间信息
            $liveInfo = (new LiveRecordingInfo())->getLiveInfo($liveId, $isInApp <= 0, $uid);
            $apiHost = Env::get('host.domain');
            $fetchData = [
                'header' => $isInApp ? json_encode($header) : '',
                'h' => $h,
                'is_in_app' => $isInApp,
                'live_id' => $liveId,
                'app_type' => $header['app-type'],
                'api_host' => $apiHost,
                'ws_gateway' => Env::get('websocket.web_gateway'),
                'user_uen' => $uen,
                'room_info' => json_encode($liveInfo, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                'week_info' => json_encode($week['week'] ?? [], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                'share_info' => $liveInfo['share_info'],
//            'send_msg_record' => $sendMegRecord,
                'sign' => $sign,
                'signPackage' => $signPackage,//微信签名
            ];
        }
        catch (\Exception $e)
        {
            $fetchData = [];
            Log::write('直播间加载失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
        }
        return $this->fetch('', $fetchData);
    }

    public function index2()
    {
        $h = input('h/d', 0);
        $liveId = input('live_id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        $isManage = input('is_manage/d', 0);
        if ($liveId <= 0)
        {
            throw new ApiException('主播未找到！');
        }
        $header = [
            'version' => $this->request->header('version'),
            'time' => $this->request->header('time'),
            'distinct-id' => $this->request->header('distinct-id'),
            'phone-version' => $this->request->header('phone-version'),
            'app-type' => $this->request->header('app-type'),
            'did' => $this->request->header('did'),
            'access-token' => $this->request->header('access-token'),
            'model' => $this->request->header('model'),
            'sign' => $this->request->header('sign'),
        ];
        $isInApp = 0;
        try
        {
            $config = config('app');
            if (isset($header['sign']) &&
                strpos($config['app_types'], $header['app-type']) !== true)
            {
                // 在准了App中
                if (IAuth::checkSignPass($header, 'app'))
                {
                    $isInApp = 1;
                }// 在直播端中
                elseif (IAuth::checkSignPass($header, 'live_app'))
                {
                    $isInApp = 2;
                }
            }
            if ($isInApp === 1 && $isManage === 1)
            {
                // 管理员端
                $isInApp = 4;
            } else if ($isInApp === 0 && $isManage === 2)
            {
                // 后台管理
                $isInApp = 3;
            }
            $userinfo = [
                'uid' => 0,
                'uen' => '',
                'nickname' => '',
                'avatar' => '',
                'sign' => 0,
                'vip_level' => 0,
                'rank_index' => 0,
            ];
            if ($header['access-token'] && in_array($isInApp, [1, 4]))
            {
                //校验token
                try
                {
                    $auth = new Auth();
                    $auth->checkRequestAuth();
                    $userinfo = [
                        'uid' => $auth->user['id'],
                        'uen' => $auth->user['uen'],
                        'nickname' => $auth->user['nickname'],
                        'avatar' => $auth->user['avatar'],
                        'sign' => 0,
                        'vip_level' => 0,
                        'rank_index' => 0,
                    ];
                    if ($auth->user['rid'])
                    {
                        $recordInfo = (new Recode())->getInfoById($auth->user['rid']);
                        $userinfo['sign'] = (int)(explode('-', $recordInfo['sun'])[0]);
                    }
                }
                catch (Exception $e)
                {
                    Log::write('直播间鉴权失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
                }
            }

            if ($this->isInWx())
            {
                //微信分享的获取微信js签名
                $signPackage = (new Jssdk())->getSignPackage();
            } else
            {
                $signPackage = [];
            }
            $signPackage = json_encode($signPackage, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            $week_info = 'null';
            if ($isInApp === 0)
            {
                //获取周运信息
                $randSign = random_int(1, 12);
                $week = (new Fortune())->weekInfo($randSign);
                if ($week['week'])
                {
                    $week_info = json_encode($week['week']);
                }
            }
            // 直播间信息
            $liveInfo = (new LiveRecordingInfo())->getLiveInfo($liveId, $isInApp <= 0, $userinfo['uid'], $isInApp > 1);
            $apiHost = Env::get('host.domain');
            $fetchData = [
                'header' => $isInApp ? json_encode($header) : 'null',
                'h' => $h,
                'is_in_app' => $isInApp,
                'live_id' => $liveId,
                'app_type' => $header['app-type'],
                'api_host' => $apiHost,
                'ws_gateway' => Env::get('websocket.web_gateway'),
                'room_info' => $liveInfo,
                'week_info' => $week_info,
                'share_info' => $liveInfo['share_info'],
                'userinfo' => $userinfo,
                'signPackage' => $signPackage,//微信签名
            ];
        }
        catch (\Exception $e)
        {
            $fetchData = [];
            Log::write('直播间加载失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
        }
        return $this->fetch('', $fetchData);
    }

    /**
     * 判断是否在微信浏览器中访问
     * @return bool
     */
    private function isInWx()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
        {
            return true;
        }
        return false;
    }
}
